<template>
  <el-dialog
    :visible="dialogVisible"
    width="25%"
    @close="closeFavorite"
  >
    <el-row
      v-for="(item,id) in dataList"
      :key="id"
    >
      <el-col>
        <span class="middle-txt">{{ item.name }} | {{ item.collectNumber }}项内容</span>
        <el-button
          v-if="!item.whetherCollection"
          class="favoriteBtn"
          type="primary"
          size="mini"
          @click="addCollect(item.id)"
        >收藏</el-button>
        <el-button
          v-else
          class="favoriteBtn"
          size="mini"
          @click="addCollect(item.id)"
        >已收藏</el-button>
        <el-divider />
      </el-col>
    </el-row>
    <el-button
      type="primary"
      @click="addFavorite"
    >
      新建收藏夹
    </el-button>
  </el-dialog>
</template>
<script>
import favorite from '@/api/favorite'
import collect from '@/api/collect'
export default {
  name: 'FavoriteList',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    closeFavorite: {
      type: Function
    },
    changeVisible: {
      type: Function
    }
  },
  data() {
    return {
      dataList: [],
      btnText: '收藏',
      btnType: 'primary',
      questionId: ''
    }
  },
  created() {
    this.questionId = this.$route.params.id
  },
  watch: {
    dialogVisible(newVal, oldVal) {
      if (newVal) {
        this.fetchList()
      }
    }
  },
  methods: {
    fetchList() {
      favorite.ownerFavorites({ questionId: this.questionId }).then(resp => {
        this.dataList = resp.data
        if (resp.data.length === 0) {
          this.dataList.push({
            id: '',
            name: '默认收藏夹',
            collectNumber: 0,
            whetherCollection: false
          })
        }
      })
    },
    addFavorite() {
      const detailVue = this.$parent.$parent
      detailVue.changeVisible(false, true)
    },
    async addCollect(favoriteId) {
      await collect.addCollect({ favoriteId, questionId: this.questionId }).then(resp => {
        this.$message({
          type: 'success',
          showClose: true,
          message: '操作成功'
        })
      })
      this.fetchList()
    }
  }
}
</script>
<style>
  .favoriteBtn{
    float: right;
    margin-right: 25px;
  }
  .middle-txt{
    vertical-align: middle;
  }
</style>
